package cn.zifangsky.interceptor;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	/**
	 * 用于验证CSRF以及验证码是否校验成功
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpSession session = request.getSession();
		String _csrfByForm = request.getParameter("_csrf"); // 表单中的值
		String _csrfBySession = String.valueOf(session.getAttribute("_csrf")); // session中的值
		Boolean codeCheck = (Boolean) session.getAttribute("codeCheck");  //验证码是否校验成功标志
		
		// 使用之后从session中删掉
		session.removeAttribute("_csrf");
		session.removeAttribute("codeCheck");

		// 验证是否存在CSRF攻击以及验证码是否校验成功
		if (StringUtils.isNotBlank(_csrfByForm) && StringUtils.isNotBlank(_csrfBySession)
				&&  codeCheck != null && _csrfByForm.equals(_csrfBySession) && codeCheck) {
			return true;
		} else {
			response.setContentType("text/html;charset=utf-8");
			response.setStatus(403);

			// 页面友好提示信息
			OutputStream oStream = response.getOutputStream();
			if(codeCheck == null || (codeCheck != null && !codeCheck)){
				oStream.write("验证码未校验通过，返回原始页面刷新后再次尝试！！！".getBytes("UTF-8"));
			}else{
				oStream.write("请不要重复提交请求，返回原始页面刷新后再次尝试！！！".getBytes("UTF-8"));
			}
			
			return false;
		}
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

}
